/**
 * 传输队列管理器
 * 支持多并发、断点续传、暂停/恢复/取消
 */
const EventEmitter = require('events');
const path = require('path');
const fs = require('fs');
const logger = require('./logger');
const config = require('./config');
const HTTPClient = require('./httpClient');

class TransferManager extends EventEmitter {
  constructor() {
    super();
    this.queue = []; // 传输队列
    this.activeTransfers = new Map(); // 活动传输任务
    this.httpClients = []; // HTTP客户端池
    this.maxConcurrent = 3; // 最大并发数
    this.taskIdCounter = 1;
    this.paused = false;
    
    // 🔥 队列限制，防止内存溢出
    this.maxQueueSize = 1000; // 最大队列任务数
    this.maxQueueMemory = 500 * 1024 * 1024; // 最大队列内存占用：500MB
    this.currentQueueMemory = 0; // 当前队列内存占用
    
    // 🔥 内存监控和动态并发调整
    this.defaultMaxConcurrent = 3; // 默认最大并发数
    this.lowMemoryMaxConcurrent = 2; // 低内存时的最大并发数
    this.memoryThreshold = 65; // 内存占用阈值（百分比）
    this.isLowMemoryMode = false; // 是否处于低内存模式
    this.memoryCheckInterval = null; // 内存检查定时器
    
    // 🔥 分批传输管理
    this.batchSize = 500; // 每批最多500个文件
    this.pendingBatches = []; // 待处理的批次队列
    this.currentBatchId = 0; // 当前批次ID
    this.batchProcessing = false; // 是否正在处理批次
    
    // 🔥 启动内存监控
    this.startMemoryMonitoring();
  }

  /**
   * 初始化HTTP客户端池
   * 🔥 支持重复调用，会先清理旧连接
   */
  async initHTTPPool(poolSize = 3) {
    this.maxConcurrent = poolSize;
    
    // 清理旧的连接
    this.cleanup();
    
    logger.info(`正在初始化HTTP客户端池，并发数: ${poolSize}`);
    
    try {
      for (let i = 0; i < poolSize; i++) {
        const client = new HTTPClient();
        
        // 监听401未授权事件
        client.on('unauthorized', () => {
          logger.error('HTTP客户端检测到401未授权错误');
          this.emit('unauthorized');
        });
        
        this.httpClients.push(client);
        logger.info(`HTTP客户端 ${i + 1}/${poolSize} 已创建`);
      }

      logger.info(`✅ HTTP客户端池初始化完成，可用客户端: ${this.httpClients.length}`);
      return true;
    } catch (error) {
      logger.error('❌ HTTP客户端池初始化失败:', error);
      this.httpClients = [];
      throw error;
    }
  }

  /**
   * 获取空闲的HTTP客户端
   * 🔥 如果未初始化，自动尝试初始化
   */
  async getAvailableClient() {
    // 如果HTTP客户端池为空，尝试初始化
    if (this.httpClients.length === 0) {
      logger.warn('HTTP客户端池未初始化，尝试自动初始化...');
      try {
        await this.initHTTPPool(this.maxConcurrent || 3);
      } catch (error) {
        logger.error('自动初始化HTTP客户端池失败:', error);
        return null;
      }
    }
    // HTTP客户端是无状态的，直接返回第一个
    return this.httpClients.length > 0 ? this.httpClients[0] : null;
  }

  /**
   * 🔥 检查队列是否可以添加任务
   */
  canAddToQueue(fileSize) {
    // 检查队列数量
    if (this.queue.length >= this.maxQueueSize) {
      logger.warn(`队列已满，当前任务数: ${this.queue.length}/${this.maxQueueSize}`);
      return {
        allowed: false,
        reason: `队列已满，最多允许 ${this.maxQueueSize} 个任务`
      };
    }
    
    // 检查内存占用（估算）
    const estimatedMemory = fileSize * 0.01; // 估算每个任务占用文件大小的1%内存
    if (this.currentQueueMemory + estimatedMemory > this.maxQueueMemory) {
      logger.warn(`队列内存占用过高: ${(this.currentQueueMemory / 1024 / 1024).toFixed(2)}MB`);
      return {
        allowed: false,
        reason: `队列内存占用过高，请等待当前任务完成`
      };
    }
    
    return { allowed: true };
  }

  /**
   * 🔥 更新队列内存占用
   */
  updateQueueMemory(fileSize, action = 'add') {
    const estimatedMemory = fileSize * 0.01;
    
    if (action === 'add') {
      this.currentQueueMemory += estimatedMemory;
    } else if (action === 'remove') {
      this.currentQueueMemory = Math.max(0, this.currentQueueMemory - estimatedMemory);
    }
    
    logger.info(`队列内存: ${(this.currentQueueMemory / 1024 / 1024).toFixed(2)}MB / ${(this.maxQueueMemory / 1024 / 1024).toFixed(2)}MB`);
  }

  /**
   * 🔥 获取队列统计信息
   */
  getQueueStats() {
    const pendingTasks = this.queue.filter(t => t.status === 'pending').length;
    const activeTasks = this.activeTransfers.size;
    const completedTasks = this.queue.filter(t => t.status === 'completed').length;
    const failedTasks = this.queue.filter(t => t.status === 'failed').length;
    
    return {
      total: this.queue.length,
      pending: pendingTasks,
      active: activeTasks,
      completed: completedTasks,
      failed: failedTasks,
      maxSize: this.maxQueueSize,
      memoryUsage: this.currentQueueMemory,
      maxMemory: this.maxQueueMemory,
      utilizationPercent: (this.queue.length / this.maxQueueSize * 100).toFixed(2)
    };
  }

  /**
   * 添加上传任务
   */
  addUploadTask(localPath, remotePath, options = {}) {
    const stats = fs.statSync(localPath);
    
    // 🔥 检查队列是否可以添加任务
    const check = this.canAddToQueue(stats.size);
    if (!check.allowed) {
      const error = new Error(check.reason);
      logger.error(`无法添加上传任务: ${path.basename(localPath)} - ${check.reason}`);
      throw error;
    }
    
    const taskId = this.taskIdCounter++;
    
    const task = {
      id: taskId,
      type: 'upload',
      localPath,
      remotePath,
      fileName: path.basename(localPath),
      fileSize: stats.size,
      transferred: 0,
      speed: 0,
      status: 'pending', // pending, active, paused, completed, failed, cancelled
      error: null,
      startTime: null,
      endTime: null,
      progress: 0,
      ...options
    };

    this.queue.push(task);
    
    // 🔥 更新队列内存占用
    this.updateQueueMemory(stats.size, 'add');
    
    this.emit('task-added', task);
    logger.logTransfer('upload', task.fileName, 'added', { taskId, fileSize: task.fileSize });

    // 🔥 延迟处理队列，避免大量任务同时添加时阻塞
    setImmediate(() => this.processQueue());

    return taskId;
  }

  /**
   * 添加下载任务
   */
  addDownloadTask(fileId, fileName, fileSize, localPath, options = {}) {
    // 🔥 检查队列是否可以添加任务
    const check = this.canAddToQueue(fileSize);
    if (!check.allowed) {
      const error = new Error(check.reason);
      logger.error(`无法添加下载任务: ${fileName} - ${check.reason}`);
      throw error;
    }
    
    const taskId = this.taskIdCounter++;
    
    const task = {
      id: taskId,
      type: 'download',
      fileId,
      localPath,
      fileName,
      fileSize,
      transferred: 0,
      speed: 0,
      status: 'pending',
      error: null,
      startTime: null,
      endTime: null,
      progress: 0,
      ...options
    };

    this.queue.push(task);
    
    // 🔥 更新队列内存占用
    this.updateQueueMemory(fileSize, 'add');
    
    this.emit('task-added', task);
    logger.logTransfer('download', task.fileName, 'added', { taskId });

    // 🔥 延迟处理队列，避免大量任务同时添加时阻塞
    setImmediate(() => this.processQueue());

    return taskId;
  }

  /**
   * 🔥 分批添加多个上传任务（带完整性验证）
   * @param {Array} files - 文件列表 [{localPath, remotePath, size, name}, ...]
   * @returns {Object} - {batchId, totalFiles, currentBatch, totalBatches}
   */
  addUploadTasksInBatches(files) {
    if (!files || files.length === 0) {
      return {
        batchId: null,
        totalFiles: 0,
        currentBatch: 0,
        totalBatches: 0,
        addedTaskIds: []
      };
    }

    const batchId = ++this.currentBatchId;
    const totalBatches = Math.ceil(files.length / this.batchSize);
    
    logger.info(`🔥 准备分批添加 ${files.length} 个文件，分为 ${totalBatches} 批，每批 ${this.batchSize} 个`);
    
    // 🔥 创建文件索引映射，用于追踪每个文件
    const fileIndexMap = new Map();
    files.forEach((file, index) => {
      const fileKey = `${file.localPath}::${file.remotePath}`;
      fileIndexMap.set(fileKey, {
        index,
        file,
        status: 'pending' // pending, added, failed, skipped
      });
    });
    
    // 将文件分批
    const batches = [];
    for (let i = 0; i < files.length; i += this.batchSize) {
      batches.push(files.slice(i, i + this.batchSize));
    }
    
    // 添加到待处理批次队列
    this.pendingBatches.push({
      batchId,
      batches,
      currentBatchIndex: 0,
      totalFiles: files.length,
      addedFiles: 0,
      failedFiles: 0,
      skippedFiles: 0,
      addedTaskIds: [],
      failedFilesList: [], // 🔥 记录失败的文件
      skippedFilesList: [], // 🔥 记录跳过的文件
      fileIndexMap, // 🔥 文件追踪映射
      startTime: Date.now()
    });
    
    logger.info(`批次 #${batchId} 已加入队列，共 ${totalBatches} 批`);
    logger.info(`📋 文件追踪已启用，将验证所有 ${files.length} 个文件`);
    
    // 开始处理批次
    this.processBatches();
    
    return {
      batchId,
      totalFiles: files.length,
      currentBatch: 1,
      totalBatches,
      message: `已创建批次 #${batchId}，将分 ${totalBatches} 批添加 ${files.length} 个文件`
    };
  }

  /**
   * 🔥 处理批次队列
   */
  async processBatches() {
    if (this.batchProcessing || this.pendingBatches.length === 0) {
      return;
    }
    
    this.batchProcessing = true;
    
    while (this.pendingBatches.length > 0) {
      const batchInfo = this.pendingBatches[0];
      const { batchId, batches, currentBatchIndex } = batchInfo;
      
      if (currentBatchIndex >= batches.length) {
        // 当前批次全部完成 - 🔥 生成完整性报告
        const endTime = Date.now();
        const duration = ((endTime - batchInfo.startTime) / 1000).toFixed(2);
        
        // 🔥 验证完整性
        const integrityReport = this.verifyBatchIntegrity(batchInfo);
        
        logger.info(`✅ 批次 #${batchId} 全部处理完成`);
        logger.info(`📊 统计: 成功 ${batchInfo.addedFiles}, 失败 ${batchInfo.failedFiles}, 跳过 ${batchInfo.skippedFiles}, 总计 ${batchInfo.totalFiles}`);
        logger.info(`⏱️  耗时: ${duration} 秒`);
        
        // 🔥 显示完整性验证结果
        if (integrityReport.isComplete) {
          logger.info(`✅ 完整性验证通过：所有 ${batchInfo.totalFiles} 个文件都已处理`);
        } else {
          logger.warn(`⚠️  完整性验证失败：有 ${integrityReport.missingCount} 个文件未处理`);
          logger.warn(`未处理文件列表: ${JSON.stringify(integrityReport.missingFiles)}`);
        }
        
        // 🔥 显示失败文件列表
        if (batchInfo.failedFiles > 0) {
          logger.warn(`⚠️  ${batchInfo.failedFiles} 个文件添加失败:`);
          batchInfo.failedFilesList.forEach((fail, idx) => {
            logger.warn(`  ${idx + 1}. ${fail.file.name}: ${fail.error}`);
          });
        }
        
        this.pendingBatches.shift();
        this.emit('batch-completed', {
          batchId,
          totalFiles: batchInfo.totalFiles,
          addedFiles: batchInfo.addedFiles,
          failedFiles: batchInfo.failedFiles,
          skippedFiles: batchInfo.skippedFiles,
          taskIds: batchInfo.addedTaskIds,
          failedFilesList: batchInfo.failedFilesList,
          integrityReport,
          duration
        });
        continue;
      }
      
      const currentBatch = batches[currentBatchIndex];
      const batchNumber = currentBatchIndex + 1;
      const totalBatches = batches.length;
      
      logger.info(`🔥 开始处理批次 #${batchId} 的第 ${batchNumber}/${totalBatches} 批，共 ${currentBatch.length} 个文件`);
      
      // 检查当前队列是否有足够空间
      const queueSpace = this.maxQueueSize - this.queue.length;
      const pendingCount = this.queue.filter(t => t.status === 'pending').length;
      
      logger.info(`当前队列状态: ${this.queue.length}/${this.maxQueueSize}，待处理: ${pendingCount}`);
      
      // 如果队列已满或待处理任务过多，等待
      if (queueSpace < 50 || pendingCount > 300) {
        logger.warn(`队列空间不足或待处理任务过多，等待处理... 空间:${queueSpace}, 待处理:${pendingCount}`);
        
        // 延迟1秒后重试
        setTimeout(() => {
          this.batchProcessing = false;
          this.processBatches();
        }, 1000);
        
        return;
      }
      
      // 添加当前批次的文件
      const addedInThisBatch = [];
      for (const file of currentBatch) {
        const fileKey = `${file.localPath}::${file.remotePath}`;
        const fileTrack = batchInfo.fileIndexMap.get(fileKey);
        
        try {
          const taskId = this.addUploadTask(file.localPath, file.remotePath, {
            batchId,
            batchNumber,
            totalBatches,
            originalIndex: fileTrack ? fileTrack.index : -1
          });
          
          addedInThisBatch.push(taskId);
          batchInfo.addedTaskIds.push(taskId);
          batchInfo.addedFiles++;
          
          // 🔥 更新文件追踪状态
          if (fileTrack) {
            fileTrack.status = 'added';
            fileTrack.taskId = taskId;
          }
          
          logger.debug(`✅ 已添加: ${file.name} (任务ID: ${taskId})`);
        } catch (error) {
          logger.error(`❌ 添加任务失败: ${file.name} (${file.localPath}) - ${error.message}`);
          
          // 🔥 记录失败的文件
          batchInfo.failedFiles++;
          batchInfo.failedFilesList.push({
            file,
            error: error.message,
            reason: this.categorizeError(error.message)
          });
          
          // 🔥 更新文件追踪状态
          if (fileTrack) {
            fileTrack.status = 'failed';
            fileTrack.error = error.message;
          }
          
          // 继续添加其他文件，不中断批次
        }
      }
      
      logger.info(`✅ 批次 #${batchId} 第 ${batchNumber}/${totalBatches} 批已添加 ${addedInThisBatch.length} 个任务`);
      
      // 更新当前批次索引
      batchInfo.currentBatchIndex++;
      
      // 发送批次进度事件
      this.emit('batch-progress', {
        batchId,
        currentBatch: batchNumber,
        totalBatches,
        addedFiles: batchInfo.addedFiles,
        totalFiles: batchInfo.totalFiles,
        addedTaskIds: addedInThisBatch
      });
      
      // 如果还有更多批次，延迟一下再处理下一批
      if (batchInfo.currentBatchIndex < batches.length) {
        setTimeout(() => {
          this.batchProcessing = false;
          this.processBatches();
        }, 500); // 延迟500ms
        return;
      }
    }
    
    this.batchProcessing = false;
  }

  /**
   * 🔥 验证批次完整性
   * 确保所有文件都已处理（added、failed 或 skipped），没有遗漏
   */
  verifyBatchIntegrity(batchInfo) {
    const { fileIndexMap, totalFiles, addedFiles, failedFiles, skippedFiles } = batchInfo;
    
    // 统计各状态的文件数
    const statusCount = {
      pending: 0,
      added: 0,
      failed: 0,
      skipped: 0
    };
    
    const missingFiles = [];
    
    // 遍历所有文件，检查状态
    fileIndexMap.forEach((trackInfo, fileKey) => {
      statusCount[trackInfo.status]++;
      
      // 记录仍处于 pending 状态的文件（未处理）
      if (trackInfo.status === 'pending') {
        missingFiles.push({
          index: trackInfo.index,
          name: trackInfo.file.name,
          localPath: trackInfo.file.localPath,
          remotePath: trackInfo.file.remotePath
        });
      }
    });
    
    // 验证总数是否匹配
    const processedCount = statusCount.added + statusCount.failed + statusCount.skipped;
    const isComplete = processedCount === totalFiles && statusCount.pending === 0;
    
    // 验证统计数据一致性
    const statsMatch = 
      statusCount.added === addedFiles &&
      statusCount.failed === failedFiles &&
      statusCount.skipped === skippedFiles;
    
    return {
      isComplete,
      statsMatch,
      totalFiles,
      processedCount,
      statusCount,
      missingCount: statusCount.pending,
      missingFiles,
      message: isComplete 
        ? `✅ 所有 ${totalFiles} 个文件都已处理`
        : `⚠️ 有 ${statusCount.pending} 个文件未处理`
    };
  }

  /**
   * 🔥 对错误进行分类
   */
  categorizeError(errorMessage) {
    if (!errorMessage) return 'unknown';
    
    const msg = errorMessage.toLowerCase();
    
    if (msg.includes('队列已满') || msg.includes('maxqueuesize')) {
      return 'queue_full';
    } else if (msg.includes('内存占用') || msg.includes('memory')) {
      return 'memory_limit';
    } else if (msg.includes('文件不存在') || msg.includes('enoent')) {
      return 'file_not_found';
    } else if (msg.includes('权限') || msg.includes('permission') || msg.includes('eacces')) {
      return 'permission_denied';
    } else if (msg.includes('网络') || msg.includes('network') || msg.includes('econnrefused')) {
      return 'network_error';
    } else if (msg.includes('超时') || msg.includes('timeout')) {
      return 'timeout';
    } else {
      return 'other';
    }
  }

  /**
   * 🔥 获取批次状态
   */
  getBatchStatus(batchId) {
    const batchInfo = this.pendingBatches.find(b => b.batchId === batchId);
    if (!batchInfo) {
      return null;
    }
    
    return {
      batchId: batchInfo.batchId,
      currentBatch: batchInfo.currentBatchIndex + 1,
      totalBatches: batchInfo.batches.length,
      addedFiles: batchInfo.addedFiles,
      failedFiles: batchInfo.failedFiles,
      skippedFiles: batchInfo.skippedFiles,
      totalFiles: batchInfo.totalFiles,
      progress: (batchInfo.addedFiles / batchInfo.totalFiles * 100).toFixed(2)
    };
  }

  /**
   * 处理传输队列
   */
  async processQueue() {
    if (this.paused) {
      return;
    }

    // 找出待处理的任务
    const pendingTasks = this.queue.filter(t => t.status === 'pending');
    
    // 检查当前活动任务数
    if (this.activeTransfers.size >= this.maxConcurrent) {
      return;
    }

    // 启动新任务
    const availableSlots = this.maxConcurrent - this.activeTransfers.size;
    const tasksToStart = pendingTasks.slice(0, availableSlots);

    for (const task of tasksToStart) {
      this.startTask(task);
    }
  }

  /**
   * 开始执行任务
   */
  async startTask(task) {
    const client = await this.getAvailableClient();
    if (!client) {
      logger.warn('没有可用的HTTP客户端');
      return;
    }

    task.status = 'active';
    task.startTime = Date.now();
    this.activeTransfers.set(task.id, { task, client });
    this.emit('task-started', task);

    logger.logTransfer(task.type, task.fileName, 'started', { taskId: task.id });

    try {
      if (task.type === 'upload') {
        await this.executeUpload(task, client);
      } else if (task.type === 'download') {
        await this.executeDownload(task, client);
      }

      // 只有任务仍在active状态时才标记为完成（可能已被暂停/取消）
      if (task.status === 'active') {
        task.status = 'completed';
        task.endTime = Date.now();
        task.progress = 100;
        this.emit('task-completed', task);
        logger.logTransfer(task.type, task.fileName, 'completed', { taskId: task.id });
        
        // 🔥 上传任务到服务器并从本地缓存移除
        await this.uploadTaskToServer(task);
        this.removeTaskFromCache(task.id);
      }
    } catch (error) {
      // 只有任务不是已取消或已暂停时才标记为失败
      if (task.status !== 'cancelled' && task.status !== 'paused') {
        task.status = 'failed';
        task.endTime = Date.now();
        
        // 🔥 保存完整的错误信息
        task.error = error.message || '未知错误';
        
        // 保存错误堆栈（用于调试）
        if (error.stack) {
          logger.error(`任务失败堆栈: ${task.fileName}`, error.stack);
        }
        
        this.emit('task-failed', task);
        logger.logTransfer(task.type, task.fileName, 'failed', { 
          taskId: task.id, 
          error: task.error,
          transferred: task.transferred,
          progress: task.progress
        });
        
        // 🔥 上传失败任务到服务器并从本地缓存移除
        try {
          await this.uploadTaskToServer(task);
          logger.info(`✅ 失败任务已上传到服务器: ${task.fileName}`);
        } catch (uploadError) {
          logger.error(`⚠️ 上传失败任务到服务器失败: ${task.fileName}`, uploadError.message);
          // 即使上传失败，也继续移除本地缓存，避免累积
        }
        
        this.removeTaskFromCache(task.id);
      } else {
        // 任务被暂停或取消，记录日志
        logger.info(`任务${task.status === 'paused' ? '已暂停' : '已取消'}: ${task.fileName}`);
      }
    } finally {
      this.activeTransfers.delete(task.id);
      // 继续处理队列
      this.processQueue();
    }
  }

  /**
   * 执行上传
   */
  async executeUpload(task, client) {
    try {
      let lastSaveTime = 0;
      const SAVE_INTERVAL = 5000; // 每5秒保存一次进度
      
      const onProgress = (progressInfo) => {
        // 检查任务是否被取消或暂停
        if (task.status === 'cancelled') {
          throw new Error('任务已取消');
        }
        if (task.status === 'paused') {
          throw new Error('任务已暂停');
        }

        task.transferred = progressInfo.transferred;
        task.speed = progressInfo.speed;
        task.progress = task.fileSize > 0 ? (progressInfo.transferred / task.fileSize) * 100 : 0;
        
        this.emit('task-progress', task);
        
        // 定期保存进度到数据库（防止崩溃丢失）
        const now = Date.now();
        if (now - lastSaveTime > SAVE_INTERVAL) {
          lastSaveTime = now;
          this.emit('save-progress-needed');
        }
      };

      logger.info(`开始上传: ${task.fileName}, 大小: ${task.fileSize}`);
      const result = await client.uploadFile(task.localPath, task.remotePath, onProgress);
      
      if (result.skipped) {
        task.status = 'completed';
        task.transferred = task.fileSize;
        task.progress = 100;
        logger.info(`文件跳过上传（已存在）: ${task.fileName}`);
      } else {
        logger.info(`文件上传完成: ${task.fileName}`);
      }
    } catch (error) {
      logger.error(`上传失败: ${task.fileName}`, error);
      throw error; // 重新抛出让外层捕获
    }
  }

  /**
   * 执行下载
   */
  async executeDownload(task, client) {
    const fs = require('fs');
    
    // 如果文件已存在，先删除（支持替换下载）
    if (fs.existsSync(task.localPath)) {
      try {
        logger.info(`删除已存在的文件: ${task.localPath}`);
        fs.unlinkSync(task.localPath);
      } catch (error) {
        logger.warn(`删除文件失败: ${error.message}`);
        // 继续尝试下载
      }
    }
    
    let lastSaveTime = 0;
    const SAVE_INTERVAL = 5000; // 每5秒保存一次进度
    
    const onProgress = (progressInfo) => {
      // 检查任务是否被取消或暂停
      if (task.status === 'cancelled') {
        throw new Error('任务已取消');
      }
      if (task.status === 'paused') {
        throw new Error('任务已暂停');
      }

      task.transferred = progressInfo.transferred;
      task.speed = progressInfo.speed;
      task.progress = task.fileSize > 0 ? (progressInfo.transferred / task.fileSize) * 100 : 0;
      
      this.emit('task-progress', task);
      
      // 定期保存进度到数据库（防止崩溃丢失）
      const now = Date.now();
      if (now - lastSaveTime > SAVE_INTERVAL) {
        lastSaveTime = now;
        this.emit('save-progress-needed');
      }
    };

    const result = await client.downloadFile(task.fileId, task.localPath, onProgress);
    
    if (result.skipped) {
      task.status = 'completed';
      task.transferred = task.fileSize;
      task.progress = 100;
    }
  }

  /**
   * 暂停任务
   */
  pauseTask(taskId) {
    const task = this.queue.find(t => t.id === taskId);
    if (task && task.status === 'active') {
      task.status = 'paused';
      this.emit('task-paused', task);
      logger.logTransfer(task.type, task.fileName, 'paused', { taskId });
    }
  }

  /**
   * 恢复任务
   */
  resumeTask(taskId) {
    const task = this.queue.find(t => t.id === taskId);
    if (task && task.status === 'paused') {
      task.status = 'pending';
      this.emit('task-resumed', task);
      logger.logTransfer(task.type, task.fileName, 'resumed', { taskId });
      this.processQueue();
    }
  }

  /**
   * 取消任务（直接从队列移除）
   */
  cancelTask(taskId) {
    const taskIndex = this.queue.findIndex(t => t.id === taskId);
    if (taskIndex !== -1) {
      const task = this.queue[taskIndex];
      
      // 🔥 从队列中移除任务
      this.queue.splice(taskIndex, 1);
      
      // 清理活动传输
      this.activeTransfers.delete(taskId);
      
      this.emit('task-cancelled', task);
      logger.logTransfer(task.type, task.fileName, 'cancelled and removed', { taskId });
      logger.info(`✅ 任务已取消并从队列移除: ${task.fileName}`);
      
      this.processQueue();
    }
  }

  /**
   * 重试任务
   */
  retryTask(taskId) {
    const task = this.queue.find(t => t.id === taskId);
    if (task && (task.status === 'failed' || task.status === 'cancelled')) {
      task.status = 'pending';
      task.error = null;
      task.transferred = 0;
      task.progress = 0;
      this.emit('task-retried', task);
      logger.logTransfer(task.type, task.fileName, 'retried', { taskId });
      this.processQueue();
    }
  }

  /**
   * 暂停所有任务
   */
  pauseAll() {
    this.paused = true;
    for (const task of this.queue) {
      if (task.status === 'active' || task.status === 'pending') {
        task.status = 'paused';
      }
    }
    this.emit('all-paused');
    logger.info('所有传输任务已暂停');
  }

  /**
   * 恢复所有任务
   */
  resumeAll() {
    this.paused = false;
    for (const task of this.queue) {
      if (task.status === 'paused') {
        task.status = 'pending';
      }
    }
    this.emit('all-resumed');
    logger.info('所有传输任务已恢复');
    this.processQueue();
  }

  /**
   * 取消所有任务（从队列移除）
   */
  cancelAll() {
    const beforeCount = this.queue.length;
    
    // 🔥 只保留已完成的任务，移除其他所有任务
    this.queue = this.queue.filter(t => t.status === 'completed');
    
    const removed = beforeCount - this.queue.length;
    
    // 清理所有活动传输
    this.activeTransfers.clear();
    
    this.emit('all-cancelled');
    logger.info(`所有传输任务已取消并移除 (移除 ${removed} 个任务)`);
  }

  /**
   * 清除已完成的任务
   */
  clearCompleted() {
    const beforeCount = this.queue.length;
    this.queue = this.queue.filter(t => t.status !== 'completed');
    const removed = beforeCount - this.queue.length;
    
    if (removed > 0) {
      this.emit('completed-cleared', removed);
      logger.info(`已清除 ${removed} 个已完成的任务`);
    }
  }

  /**
   * 获取任务列表
   */
  getTasks() {
    return this.queue;
  }

  /**
   * 获取任务
   */
  getTask(taskId) {
    return this.queue.find(t => t.id === taskId);
  }

  /**
   * 获取统计信息
   */
  getStats() {
    const stats = {
      total: this.queue.length,
      pending: 0,
      active: 0,
      paused: 0,
      completed: 0,
      failed: 0,
      cancelled: 0
    };

    for (const task of this.queue) {
      stats[task.status]++;
    }

    return stats;
  }

  /**
   * 保存队列状态（用于崩溃恢复）
   */
  saveState() {
    const state = {
      queue: this.queue.map(task => {
        // 传输中的任务恢复为pending状态，下次启动会自动继续
        let savedStatus = task.status;
        if (task.status === 'active') {
          savedStatus = 'pending';
          logger.info(`保存任务状态: ${task.fileName} (active -> pending) 进度: ${task.progress.toFixed(1)}%`);
        }
        
        return {
          ...task,
          status: savedStatus,
          // 保存当前传输进度，用于断点续传
          savedProgress: task.progress,
          savedTransferred: task.transferred,
          lastSaveTime: Date.now()
        };
      }),
      maxConcurrent: this.maxConcurrent,
      timestamp: Date.now()
    };
    return state;
  }

  /**
   * 恢复队列状态
   */
  restoreState(state) {
    if (state && state.queue) {
      const originalCount = state.queue.length;
      
      // 🔥 性能优化：只恢复未完成的任务，自动清除已完成和已取消的任务
      // 注意：取消的任务不应该恢复，应该被清除
      const validStatuses = ['pending', 'paused', 'failed'];
      const tasksToRestore = state.queue.filter(task => {
        return validStatuses.includes(task.status);
      });
      
      const removedCount = originalCount - tasksToRestore.length;
      if (removedCount > 0) {
        logger.info(`🧹 自动清除 ${removedCount} 个已完成/已取消的任务`);
      }
      
      // 🔥 限制恢复数量：最多恢复 100 个任务，防止内存溢出
      const MAX_RESTORE_TASKS = 100;
      let finalTasks = tasksToRestore;
      
      if (tasksToRestore.length > MAX_RESTORE_TASKS) {
        logger.warn(`⚠️ 任务数量过多 (${tasksToRestore.length})，仅恢复最近的 ${MAX_RESTORE_TASKS} 个任务`);
        // 按创建时间倒序排序，取最新的任务
        finalTasks = tasksToRestore
          .sort((a, b) => (b.created_at || 0) - (a.created_at || 0))
          .slice(0, MAX_RESTORE_TASKS);
      }
      
      // 恢复任务队列
      this.queue = finalTasks.map(task => {
        // 恢复保存的进度信息
        if (task.savedProgress !== undefined) {
          task.progress = task.savedProgress;
          task.transferred = task.savedTransferred || 0;
        }
        
        // 清理保存时的临时字段
        delete task.savedProgress;
        delete task.savedTransferred;
        delete task.lastSaveTime;
        
        return task;
      });
      
      this.maxConcurrent = state.maxConcurrent || 3;
      
      // 找出最大的taskId
      const maxId = this.queue.length > 0 ? Math.max(...this.queue.map(t => t.id), 0) : 0;
      this.taskIdCounter = maxId + 1;

      // 统计各状态任务
      const pending = this.queue.filter(t => t.status === 'pending').length;
      const paused = this.queue.filter(t => t.status === 'paused').length;
      const failed = this.queue.filter(t => t.status === 'failed').length;

      logger.info(`✅ 已恢复 ${this.queue.length} 个传输任务 (待传输: ${pending}, 已暂停: ${paused}, 失败: ${failed})`);
      this.emit('state-restored', this.queue.length);
      
      // 🔥 安全恢复：延迟启动，且限制初始并发
      if (pending > 0) {
        const autoStartCount = Math.min(pending, this.maxConcurrent);
        logger.info(`🚀 将在 3 秒后自动开始处理前 ${autoStartCount} 个待传输任务...`);
        setTimeout(() => {
          logger.info('开始处理队列...');
          this.processQueue();
        }, 3000); // 延迟 3 秒启动
      }
    }
  }

  /**
   * 上传任务到服务器（仅完成/失败的任务）
   */
  async uploadTaskToServer(task) {
    try {
      // 获取配置信息
      const appConfig = config.get();
      if (!appConfig || !appConfig.serverUrl || !appConfig.token) {
        logger.warn('未配置服务器信息，跳过上传任务到服务器');
        return;
      }

      const clientId = appConfig.clientId || `client_${Date.now()}`;
      
      // 准备任务数据
      const taskData = {
        client_id: clientId,
        task_id: task.id,
        type: task.type,
        file_name: task.fileName,
        local_path: task.localPath || '',
        remote_path: task.remotePath || '',
        file_id: task.fileId || null,
        file_size: task.fileSize || 0,
        transferred: task.transferred || 0,
        progress: Math.round(task.progress || 0),
        speed: task.speed || 0,
        status: task.status, // 'completed' or 'failed'
        error: task.error || null, // 🔥 包含错误信息
        start_time: task.startTime || null,
        end_time: task.endTime || Date.now()
      };

      // 🔥 记录失败任务的详细信息
      if (task.status === 'failed') {
        logger.warn(`⚠️ 上传失败任务到服务器: ${task.fileName}`, {
          error: task.error,
          transferred: `${task.transferred}/${task.fileSize}`,
          progress: `${Math.round(task.progress || 0)}%`
        });
      }

      // 发送到服务器
      const axios = require('axios');
      const response = await axios.post(
        `${appConfig.serverUrl}/api/transfer-queue/save`,
        taskData,
        {
          headers: {
            'Authorization': `Bearer ${appConfig.token}`,
            'Content-Type': 'application/json'
          },
          timeout: 10000
        }
      );

      if (response.data.success) {
        logger.info(`✅ 任务已上传到服务器: ${task.fileName} (${task.status})`);
      } else {
        logger.error(`❌ 服务器返回错误: ${response.data.message}`);
      }
    } catch (error) {
      logger.error(`上传任务到服务器失败: ${task.fileName}`, error.message);
      // 不抛出错误，避免影响任务流程
    }
  }

  /**
   * 从本地缓存移除任务
   */
  removeTaskFromCache(taskId) {
    const index = this.queue.findIndex(t => t.id === taskId);
    if (index !== -1) {
      const task = this.queue[index];
      this.queue.splice(index, 1);
      
      // 🔥 更新队列内存占用
      this.updateQueueMemory(task.fileSize, 'remove');
      
      logger.info(`从本地缓存移除任务: ${task.fileName}`);
      this.emit('task-removed', task);
    }
  }

  /**
   * 🔥 启动内存监控
   */
  startMemoryMonitoring() {
    // 🔥 优化：每30秒检查一次内存使用率，减少CPU占用
    this.memoryCheckInterval = setInterval(() => {
      this.checkMemoryUsage();
    }, 30000);
    
    logger.info('内存监控已启动（每30秒检查）');
  }

  /**
   * 🔥 检查内存使用率
   */
  checkMemoryUsage() {
    try {
      const os = require('os');
      const totalMemory = os.totalmem();
      const freeMemory = os.freemem();
      const usedMemory = totalMemory - freeMemory;
      const memoryUsagePercent = (usedMemory / totalMemory) * 100;
      
      // 判断是否超过内存阈值
      const isHighMemory = memoryUsagePercent > this.memoryThreshold;
      
      // 如果内存状态发生变化
      if (isHighMemory && !this.isLowMemoryMode) {
        // 切换到低内存模式
        this.isLowMemoryMode = true;
        logger.warn(`内存占用过高 (${memoryUsagePercent.toFixed(2)}%)，降低并发数从 ${this.maxConcurrent} 到 ${this.lowMemoryMaxConcurrent}`);
        this.adjustConcurrency(this.lowMemoryMaxConcurrent);
        
      } else if (!isHighMemory && this.isLowMemoryMode) {
        // 恢复正常模式
        this.isLowMemoryMode = false;
        logger.info(`内存占用恢复正常 (${memoryUsagePercent.toFixed(2)}%)，恢复并发数到 ${this.defaultMaxConcurrent}`);
        this.adjustConcurrency(this.defaultMaxConcurrent);
      }
      
      // 记录内存状态（每分钟记录一次详细信息）
      if (!this.lastMemoryLogTime || Date.now() - this.lastMemoryLogTime > 60000) {
        this.lastMemoryLogTime = Date.now();
        logger.info(`内存使用率: ${memoryUsagePercent.toFixed(2)}% (${(usedMemory / 1024 / 1024 / 1024).toFixed(2)}GB / ${(totalMemory / 1024 / 1024 / 1024).toFixed(2)}GB), 当前并发: ${this.maxConcurrent}`);
      }
      
    } catch (error) {
      logger.error('检查内存使用率失败:', error);
    }
  }

  /**
   * 🔥 动态调整并发数
   */
  adjustConcurrency(newMaxConcurrent) {
    const oldMaxConcurrent = this.maxConcurrent;
    this.maxConcurrent = newMaxConcurrent;
    
    // 如果降低了并发数，需要等待部分任务完成
    if (newMaxConcurrent < oldMaxConcurrent) {
      logger.info(`并发数已降低: ${oldMaxConcurrent} -> ${newMaxConcurrent}, 当前活动任务: ${this.activeTransfers.size}`);
      
      // 注意：不取消任何任务，只是不启动新任务直到活动任务数降到新的限制以下
      this.emit('concurrency-reduced', {
        old: oldMaxConcurrent,
        new: newMaxConcurrent,
        activeCount: this.activeTransfers.size
      });
      
    } else if (newMaxConcurrent > oldMaxConcurrent) {
      logger.info(`并发数已恢复: ${oldMaxConcurrent} -> ${newMaxConcurrent}, 队列中待处理任务: ${this.queue.filter(t => t.status === 'pending').length}`);
      
      // 恢复并发数后，立即尝试处理队列
      this.processQueue();
      
      this.emit('concurrency-increased', {
        old: oldMaxConcurrent,
        new: newMaxConcurrent,
        pendingCount: this.queue.filter(t => t.status === 'pending').length
      });
    }
  }

  /**
   * 🔥 获取内存监控状态
   */
  getMemoryStatus() {
    try {
      const os = require('os');
      const totalMemory = os.totalmem();
      const freeMemory = os.freemem();
      const usedMemory = totalMemory - freeMemory;
      const memoryUsagePercent = (usedMemory / totalMemory) * 100;
      
      return {
        total: totalMemory,
        used: usedMemory,
        free: freeMemory,
        usagePercent: memoryUsagePercent,
        threshold: this.memoryThreshold,
        isLowMemoryMode: this.isLowMemoryMode,
        currentConcurrency: this.maxConcurrent,
        defaultConcurrency: this.defaultMaxConcurrent
      };
    } catch (error) {
      logger.error('获取内存状态失败:', error);
      return null;
    }
  }

  /**
   * 清理资源
   */
  cleanup() {
    // 🔥 清理内存监控定时器
    if (this.memoryCheckInterval) {
      clearInterval(this.memoryCheckInterval);
      this.memoryCheckInterval = null;
      logger.info('内存监控已停止');
    }
    
    // 清理所有HTTP客户端
    this.httpClients = [];
    this.activeTransfers.clear();
    logger.info('传输管理器已清理');
  }
}

module.exports = new TransferManager();
